package arocms.upload;

import arocms.business.FileDAO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;

import arocms.business.File;
import org.hibernate.Hibernate;
import arocms.util.FileSizeFormatter;

public class UploadFileAction extends Action {
    
    private final static String SUCCESS = "success";
    private final static String ERROR = "failure";
    
    public ActionForward execute(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        File file = new File();
        UploadFileForm uData = (UploadFileForm) form;
        file.setTitle(uData.getTitle());
        file.setDescription(uData.getDescription());
        file.setFilename(uData.getFile().getFileName());
        file.setFilesize(FileSizeFormatter.auto(uData.getFile().getFileSize()));
        file.setFiletype(uData.getFile().getContentType());
        file.setFilebin(Hibernate.createBlob(uData.getFile().getInputStream()));
        new FileDAO().createOrUpdate(file);
        if (file.getId()==null) {
            return mapping.findForward(ERROR);
        } else {
            return mapping.findForward(SUCCESS);
        }
    }
}
